<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/27
 * Time: 22:34
 * @link http://www.lmterp.cn
 */

namespace app\command;

use app\common\model\Orders;
use app\common\model\OrdersDetail;
use app\common\service\report\ReportService;
use think\console\input\Option;
use think\facade\Log;
use function PHPUnit\contains;

/**
 * 统计订单
 * Class StatOrder
 * @package app\command
 */
class StatOrder extends BaseCommand
{
    protected function configure()
    {
        $this->setName('statorder')
            ->addOption("start_date", null, Option::VALUE_REQUIRED, "开始统计时间，默认为昨天")
            ->addOption("end_date", null, Option::VALUE_REQUIRED, "结束统计时间");
    }

    /**
     * 开始时间
     * @var string
     */
    protected $startDate;

    /**
     * 结束时间
     * @var string
     */
    protected $endDate;

    protected function handler()
    {
        $this->startDate = $this->input->hasOption("start_date")
            ? $this->input->getOption("start_date")
            : date('Y-m-d', strtotime("-1day"));
        $this->endDate = $this->input->hasOption("end_date")
            ? $this->input->getOption("end_date")
            : date('Y-m-d');

        Log::info("开始统计【{$this->startDate} - {$this->endDate}】订单销量");
        $this->statByAccount();
        $this->statBySku();
        $this->statByCountry();
        Log::info("完成统计【{$this->startDate} - {$this->endDate}】订单销量");
    }

    /**
     * 按账号统计订单
     * @date 2020/09/27
     * @author longli
     */
    protected function statByAccount()
    {
        $where = $this->getWhere();
        $orders = Orders::field(["COUNT(account_id) qty", "SUM(total_price_rmb) - SUM(refund) total_price", "account_id", "'{$this->startDate}' stat_date"])
            ->where($where)
            ->group(["account_id"])
            ->select();
        $service = ReportService::getInstance();
        foreach($orders as $order)
        {
            $service->addStatOrder([
                'ref_key' => 'account_id',
                'ref_value' => $order->account_id,
                'total_price' => $order->total_price,
                'qty' => $order->qty, // 账号订单总数
                'stat_date' => $order->stat_date,
            ]);
        }
    }

    /**
     * 按 sku 统计
     * @date 2021/03/25
     * @author longli
     */
    protected function statBySku()
    {
        $where = $this->getWhere();
        $orders = Orders::field(['sku', 'SUM(qty) qty', 'SUM(d.total_price_rmb) total_price', "'{$this->startDate}' stat_date"])
            ->alias('o')
            ->join(OrdersDetail::getTable() . ' d', 'd.order_id=o.order_id')
            ->where($where)
            ->group('d.sku')
            ->select();
        $service = ReportService::getInstance();
        foreach($orders as $order)
        {
            if($order->total_price < 1) continue;
            $service->addStatOrder([
                'ref_key' => 'sku',
                'ref_value' => $order->sku,
                'total_price' => $order->total_price,
                'qty' => $order->qty,
                'stat_date' => $order->stat_date,
            ]);
        }
    }

    /**
     * 按国家统计
     * @date 2021/03/25
     * @author longli
     */
    protected function statByCountry()
    {
        $where = $this->getWhere();
        $orders = Orders::field(['buyer_country_code', 'SUM(qty) qty', 'SUM(d.total_price_rmb) total_price', "'{$this->startDate}' stat_date"])
            ->alias('o')
            ->join(OrdersDetail::getTable() . ' d', 'd.order_id=o.order_id')
            ->where($where)
            ->group('buyer_country_code')
            ->select();
        $service = ReportService::getInstance();
        foreach($orders as $order)
        {
            if($order->total_price < 1) continue;
            $service->addStatOrder([
                'ref_key' => 'buyer_country_code',
                'ref_value' => $order->buyer_country_code,
                'total_price' => $order->total_price,
                'qty' => $order->qty,
                'stat_date' => $order->stat_date,
            ]);
        }
    }

    /**
     * 组装 where 条件
     * @return array[]
     * @date 2021/03/25
     * @author longli
     */
    private function getWhere()
    {
        $where = [
            ["order_source_create_time", "egt", $this->startDate],
            ["total_price", "gt", 0],
            ["order_status", "not in", [
                Orders::ORDER_CANCEL,
                Orders::ORDER_REJECT,
                ORders::ORDER_FALSE,
                Orders::ORDER_RETURN
                ]
            ]
        ];
        if(!empty($this->endDate)) $where[] = ["order_source_create_time", "<", $this->endDate];
        return $where;
    }
}
